package UDPServer;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        //客户端端口由系统自动分配，无需手动配置
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    //需要手动输入客户端的IP和端口
    public void start() throws IOException {
        System.out.println("Client start! ");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("-> ");
            String request = scanner.next();
            if (request.equals("exit")) break;
            //1. 发送请求，将用户输入的字符串构造成UDP数据报，进行发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    /*request.length() error*/
                    //不是字符串的长度，而是字符串转换为字节后的长度，否则传输的长度有误，导致传输内容不完整
                    request.getBytes().length,
                    InetAddress.getByName(this.serverIP),this.serverPort);
            socket.send(requestPacket);
            //2. 从服务器读取响应resp
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);//输出型参数
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9191);
        client.start();
    }
}
